﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Extensions;
using IdentityServer4.Test;
using Ids4Review.AuthorizationServer.Data.Core;
using Ids4Review.AuthorizationServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace Ids4Review.AuthorizationServer.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        //private readonly TestUserStore _testUserStore;
        public AccountController(
            //TestUserStore testUserStore,
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager
            )
        {
            //_testUserStore = testUserStore;
            _userManager = userManager;
            _signInManager = signInManager;
        }
        public IActionResult Login(string returnUrl = null)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public async Task<IActionResult> SignIn(LoginVm vm, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                AuthenticationProperties props = null;
                //var user = _testUserStore.FindByUsername("Zj");
                var user = await _userManager.FindByNameAsync(vm.UserName);
                if (user == null)
                {
                    throw new Exception($"User whose name equals {vm.UserName} does not exist.");
                }
                //var rt = _testUserStore.ValidateCredentials(vm.UserName, vm.Password);
                var rt =await _userManager.CheckPasswordAsync(user,vm.Password);
                if (rt)
                {
                    if (vm.RememberMe)
                    {
                        props = new AuthenticationProperties()
                        {
                            IsPersistent = vm.RememberMe,
                            ExpiresUtc = DateTimeOffset.UtcNow.AddSeconds(30)
                        };
                    }
                    //await AuthenticationManagerExtensions.SignInAsync(HttpContext, user.SubjectId, user.Username, props);
                    await _signInManager.SignInAsync(user,props);
                    return Redirect(returnUrl);
                }
                return BadRequest();
            }
            else
            {
                return BadRequest();
            }
        }
        public async Task<IActionResult> SignOut()
        {
            //await HttpContext.SignOutAsync();
            await _signInManager.SignOutAsync();
            return RedirectToAction("Index", "Home");
        }
    }
}